package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {
    // 1.创建路由
    router := gin.Default()
   // 2.绑定路由规则，执行的函数
   // gin.Context，封装了request和response
   router.GET("/", func(c *gin.Context) {
      c.String(http.StatusOK, "hello World2!")
   })

    router.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })

    //router.GET("/someGet", getting)
    //router.POST("/somePost", posting)
    //router.PUT("/somePut", putting)
    //router.DELETE("/someDelete", deleting)
    //router.PATCH("/somePatch", patching)
    //router.HEAD("/someHead", head)
    //router.OPTIONS("/someOptions", options)


    // 此规则能够匹配/user/john这种格式，但不能匹配/user/ 或 /user这种格式
    router.GET("/user/:name", func(c *gin.Context) {
        name := c.Param("name")
        c.String(http.StatusOK, "Hello %s", name)
    })

    // 但是，这个规则既能匹配/user/john/格式也能匹配/user/john/send这种格式
    // 如果没有其他路由器匹配/user/john，它将重定向到/user/john/
    router.GET("/user/:name/*action", func(c *gin.Context) {
        name := c.Param("name")
        action := c.Param("action")
        message := name + " is " + action
        c.String(http.StatusOK, message)
    })

    // 匹配的url格式:  /welcome?firstname=Jane&lastname=Doe
    router.GET("/welcome", func(c *gin.Context) {
        firstname := c.DefaultQuery("firstname", "Guest")
        lastname := c.Query("lastname") // 是 c.Request.URL.Query().Get("lastname") 的简写

        c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
    })


    router.POST("/form_post", func(c *gin.Context) {
        message := c.PostForm("message")
        nick := c.DefaultPostForm("nick", "anonymous") // 此方法可以设置默认值

        c.JSON(200, gin.H{
            "status":  "posted",
            "message": message,
            "nick":    nick,
        })
    })

    router.POST("/post", func(c *gin.Context) {

        id := c.Query("id")
        page := c.DefaultQuery("page", "0")
        name := c.PostForm("name")
        message := c.PostForm("message")

        fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
    })

   // 3.监听端口，默认在8080
   // Run("里面不指定端口号默认为8080") 
    router.Run(":8000")
}